package com.redstar.interesting.common.starter.config;

import com.redstar.interesting.common.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lihongxing
 */
@Slf4j
@Configuration
public class JvmLogConfigurer implements InitializingBean {


    @Autowired
    private Map<String, ThreadPoolExecutor> threadPoolExecutorMap;


    @Override
    public void afterPropertiesSet() {
        for (Map.Entry<String, ThreadPoolExecutor> entry : threadPoolExecutorMap.entrySet()) {
            Runtime.getRuntime().addShutdownHook(new Thread(() -> doShutDownThreadPool(entry.getKey(), entry.getValue())));
        }
    }

    private void doShutDownThreadPool(String threadPoolName, ThreadPoolExecutor threadPool) {
        log.info("{}线程池开始关闭。。。", threadPoolName);
        threadPool.shutdown();
        try {
            //等待30秒之后，如果还未关闭，则强制关闭
            if (!threadPool.awaitTermination(Constants.THIRTY, TimeUnit.SECONDS)) {
                threadPool.shutdownNow();
            }
        }catch (InterruptedException e) {
            log.error("interrupted exception error ...", e);
        }
        log.info("{}线程池关闭成功。。。", threadPoolName);
    }
}
